<?php

namespace app\api\server;

use app\api\server\Goods as ServerGoods;
use app\common\controller\Server;
use app\common\model\Cart as ModelCart;
use app\common\model\goods\Goods;
use app\common\model\User;

/**
 * 购物车逻辑
 */
class Cart
{


    /**
     * 添加购物车
     *
     */
    public static function addCart($data, $uid, $type)
    {
        extract($data);
        try {
            if ($num <= 0) {
                exception('请输入数量');
            }
            $goods = Goods::get($goods_id);

            if (!$goods) {
                exception('商品不存在');
            }
            $data['user_id'] = $uid;
            $data['type'] = $type;
            $data['unit'] = $unit;

            $cart =  ModelCart::get([
                'user_id' => $uid,
                'goods_id' => $goods_id,
                'type' => $type,
                'unit' => $unit,
            ]);
            if ($cart) {
                switch ($add_sub) {
                    case 0:
                        $cart->num = $num;
                        $cart->save();
                        break;
                    case 1:
                        if ($type == 2) {
                            $cart->num = $num;
                            $cart->save();
                        } else {
                            $cart->setInc('num', $num);
                        }
                        break;
                    case 2:
                        $cart->setDec('num', $num);
                        break;
                }
                if ($cart->num <= 0) {
                    $cart->delete();
                }
            } else {
                $cart = ModelCart::create($data, true);
            }
            return $cart->id;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }
    public static function lists($uid)
    {
        $lists = ModelCart::with(['goods'])->where('user_id', $uid)->paginate();
        return $lists;
    }

    //获取购物车下单商品信息
    public static function getGoods($ids, $user)
    {

        $cart_goods = ModelCart::with('goods')->where('user_id', $user['id'])->whereIn('id', $ids)->select();
        foreach ($cart_goods as $v) {
            if (!isset($v->goods) || !$v->goods) {
                exception('商品不存在，无法下单');
            }
            if ($v->goods->stock < $v->num) {
                exception('商品【' . $v->goods->title . '】库存不足，无法下单');
            }
            if ($v->goods->deletetime != null) {
                exception('商品【' . $v->goods->title . '】已删除，无法下单');
            }
            $fee_array = ServerGoods::vip_price($v->goods, $user['group_id'], $v->num);
            $v->discount_amount = $fee_array['discount_amount'];
            $v->pay_fee = $fee_array['total_fee'];
            $v->vip_price = $fee_array['vip_price'];
            $v->performance = $fee_array['performance'];
        }
        return $cart_goods;
    }
}
